﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using Agents.Data;

namespace Agents
{
    public partial class StockList : System.Web.UI.Page
    {
        #region Event Handlers

        public void Page_Load(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// Redirects the admin back to his homepage when the "back" button is pressed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void backBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/AdminMenu.aspx");
        }

        /// <summary>
        /// Handles the page indexing
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        public void dgProducts_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            // Updating the current page for the data grid to display.
            dgProducts.CurrentPageIndex = e.NewPageIndex;

            // Binding the data.
            dgProducts.DataBind();
        }

        /// <summary>
        /// Occurs when a row in the stock list table is bound, and paints
        /// it in red if there is a notification for the product.
        /// </summary>
        /// <param name="e"></param>
        public void dgProducts_ItemDataBound(Object sender, DataGridItemEventArgs e)
        {
            if ((e.Item.ItemType == ListItemType.Item) ||
                (e.Item.ItemType == ListItemType.AlternatingItem))
            {
                int productId =
                 Convert.ToInt32(DataBinder.Eval(e.Item.DataItem,
                 "Id"));

                // Check if there is a notification for this product
                Queries queries = new Queries();

                if (queries.GetProduct(productId).Notifications.Count > 0)
                {
                    // Color the foreground of the row red
                    e.Item.ForeColor = Color.Red;

                    // Add tool tip to tell the user there is a notification for this product
                    e.Item.ToolTip = "קיימת התראה על המוצר. לחץ פעמיים על מנת לצפות בה.";

                    // Add the double click event to show the notification
                    int notificationId = queries.GetProduct(productId).
                        Notifications.FirstOrDefault().Id;

                    String script = String.Format(
                        "PopupCenter('NotificationDetails.aspx?notificationId={0}'," +
                        "'מערכת סוכנים',420, 220, true);", notificationId);

                    e.Item.Attributes.Add("ondblclick", script);
                    e.Item.Style["cursor"] = "hand";
                }
            }
        }

        #endregion
    }
}